<template>
  <a-drawer
    :width="900"
    placement="right"
    :visible="visible"
    :after-visible-change="afterVisibleChange"
    @close="onClose"
    class="form-drawer"
    :closable="false"
  >
    <a-tabs :style="{ height: '100%' }" class="" @tabClick="typeClick" tabPosition="left">
      <a-tab-pane v-for="item in tabList" :key="item.value" :tab="item.name">
        <div class="ant-descriptions-title">{{ item.name }}</div>
        <a-form-model
          :model="ruleForm"
          :ref="item.value"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          v-if="item.value === 'user'"
        >
          <a-form-model-item
            label="头像："
            prop="avatar"
            :rules="{ required: true, message: '请上传头像' }"
          >
            <upload-image v-model="ruleForm.avatar" uploadMode="manual" />
          </a-form-model-item>
          <a-form-model-item label="登录账号：" prop="loginName" :rules="{ required: true }">
            <span> {{ ruleForm.loginName }} </span>
          </a-form-model-item>
          <a-form-model-item
            label="员工姓名："
            prop="name"
            :rules="{ required: true, message: '请输入员工姓名' }"
          >
            <a-input v-model="ruleForm.name" placeholder="请输入" allow-clear></a-input>
          </a-form-model-item>
          <a-form-model-item label="员工工号：" prop="jobNumber" :rules="{ required: true }">
            <span> {{ ruleForm.jobNumber }} </span>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 13, offset: 3 }">
            <a-button type="primary" @click="onSubmit">更新信息</a-button>
          </a-form-model-item>
        </a-form-model>
        <a-form-model
          :model="ruleForm"
          :ref="item.value"
          layout="vertical"
          v-if="tabActive === 'password'"
          key="password"
          :rules="rules"
        >
          <a-form-model-item
            label="原密码"
            prop="password"
            name="password"
            :wrapperCol="wrapperCol"
          >
            <a-row>
              <a-col :span="24">
                <a-input-password v-model="ruleForm.password" placeholder="请输入" allow-clear />
              </a-col>
            </a-row>
          </a-form-model-item>
          <a-form-model-item label="新密码" prop="newPassword" name="newPassword">
            <a-row type="flex" align="middle">
              <a-col :span="13">
                <a-input-password
                  v-model="ruleForm.newPassword"
                  @change="passwordInputChange"
                  placeholder="请输入6~20位数字字母组合"
                  allow-clear
                  :maxLength="20"
                />
              </a-col>
              <a-col
                :span="10"
                style="margin-left: 10px; display: flex"
                v-if="ruleForm.newPassword"
              >
                <div class="progress">
                  <template v-for="n in 3">
                    <div
                      class="progress-item"
                      :key="n"
                      :style="{
                        backgroundColor:
                          ([0, 1].includes(state.passwordLevel) || state.passwordLevel > 1) &&
                          n == 1
                            ? passwordLevelColor[0]
                            : (state.passwordLevel == 2 || state.passwordLevel > 2) && n == 2
                              ? passwordLevelColor[2]
                              : state.passwordLevel == 3 && n == 3
                                ? passwordLevelColor[3]
                                : ''
                      }"
                    />
                  </template>
                </div>
                <div :class="passwordLevelClass">{{ passwordLevelName }}</div>
              </a-col>
            </a-row>
          </a-form-model-item>
          <a-form-model-item label="确认新密码" prop="confirmPassword" :wrapperCol="wrapperCol">
            <a-row type="flex" align="middle">
              <a-col :span="24">
                <a-input-password
                  v-model="ruleForm.confirmPassword"
                  placeholder="请输入"
                  allow-clear
                />
              </a-col>
            </a-row>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type="primary" @click="pwdSubmitHandler" :loading="submitLoading">
              提交
            </a-button>
          </a-form-model-item>
        </a-form-model>
        <a-form-model
          :ref="item.value"
          layout="vertical"
          v-if="tabActive === 'phone'"
          key="phone"
          :model="phoneRuleForm"
        >
          <div class="ant-descriptions-row">
            <div class="ant-descriptions-item">
              <div class="ant-descriptions-item-label"></div>
              <div class="ant-descriptions-item-content">
                <div class="user-phone">已绑定手机：{{ ruleForm.phone }}</div>
                <!-- <a-button type="link">修改</a-button> -->
              </div>
            </div>
          </div>
          <a-form-model-item
            label="绑定新手机号码"
            prop="phone"
            name="phone"
            :wrapperCol="wrapperCol"
            :rules="[
              { required: true, message: '请输入手机号码' },
              { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' }
            ]"
          >
            <a-input v-model="phoneRuleForm.phone" placeholder="请输入" allow-clear />
          </a-form-model-item>
          <a-form-model-item
            label="验证码"
            :wrapperCol="wrapperCol"
            prop="randomCode"
            :rules="[{ required: true, message: '请输入验证码' }]"
          >
            <a-row :gutter="16">
              <a-col class="gutter-row" :span="16">
                <a-input
                  placeholder="请输入"
                  v-model="phoneRuleForm.randomCode"
                  allow-clear
                >
                </a-input>
              </a-col>
              <a-col class="gutter-row" :span="8">
                <a-button
                  class="getCaptcha"
                  type="primary"
                  size="small"
                  :disabled="state.smsSendBtn"
                  @click.stop.prevent="getCaptcha"
                  v-text="(!state.smsSendBtn && '获取验证码') || state.time + ' s'"
                ></a-button>
              </a-col>
            </a-row>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type="primary" @click="phoneSubmitHandler" :loading="submitLoading">
              提交
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-tab-pane>
    </a-tabs>
  </a-drawer>
</template>

<script>
import UploadImage from '@/components/UploadImage'
import { mapGetters } from 'vuex'
import { editUser, userUpdatePwd, userUpdatePhone, msmCode } from '@/api/system'
import store from '@/store'
import { mixinDevice } from '@/utils/mixin.js'
const levelNames = {
  0: '低',
  1: '低',
  2: '中',
  3: '强'
}
const levelClass = {
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success'
}
const levelColor = {
  0: '#FCDEA0',
  1: '#FCDEA0',
  2: '#9BDF7C',
  3: '#52C41A'
}
const tabList = [
  { name: '个人资料', value: 'user' },
  { name: '修改密码', value: 'password' },
  // { name: '手机号码绑定', value: 'phone' }
]
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&._])[A-Za-z\d@$!%*#?&._]{8,20}$/
export default {
  name: 'UserInfo',
  mixins: [mixinDevice],
  data () {
    return {
      visible: false,
      tabList,
      ruleForm: {
        password: '',
        newPassword: '',
        confirmPassword: ''
      },
      phoneRuleForm: {
        phone: '',
        randomCode: ''
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 13 },
      rules: {
        avatar: [{ required: true, message: '请上传头像' }],
        loginName: [{ required: true, message: '请输入登录账号' }],
        name: [{ required: true, message: '请输入员工姓名' }],
        jobNumber: [{ required: true, message: '请输入员工工号' }],
        password: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
        newPassword: [{ required: true, validator: this.newPasswordCheck }],
        confirmPassword: [{ validator: this.handlePasswordCheck, required: true }]
      },
      pwdForm: {},
      state: {
        time: 60,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      passwordLevelColor: levelColor,
      tabActive: tabList[0].value || ['user'],
      submitLoading: false
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    passwordLevelClass () {
      return levelClass[this.state.passwordLevel]
    },
    passwordLevelName () {
      return levelNames[this.state.passwordLevel]
    }
  },
  methods: {
    getCaptcha () {
      const { state, $message } = this
      this.$refs.phone[0].validateField('phone', function (valid) {
        if (!valid) {
          state.smsSendBtn = true
          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = $message.loading('验证码发送中..', 0)

          msmCode({ type: '2' })
            .then((res) => {
              setTimeout(hide, 2500)
              // $notification['success']({
              //   message: '提示',
              //   description: '验证码获取成功，您的验证码为：' + res.result.captcha,
              //   duration: 8
              // })
            })
            .catch(() => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
            })
        }
      })
    },
    passwordInputChange () {
      const value = this.ruleForm.newPassword
      let level = 0
      if (/\d/.test(value)) {
        level++
      }
      // 判断这个字符串中有没有数字
      if (/[a-zA-Z]/.test(value)) {
        level++
      }
      if (passwordRegex.test(value)) {
        level++
      }
      
      this.state.passwordLevel = level
    },
    newPasswordCheck (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入新密码'))
      } else if (value.length < 8) {
        callback(new Error('请输入请输入8~20位数密码'))
      } else if(!passwordRegex.test(value)){
        callback('请输入包含字母大小写、特殊字符、数字的三种组合')
      }else{
        callback()
      }
    },
    handlePasswordCheck (rule, value, callback) {
      const password = this.ruleForm.newPassword
      console.log('value', value)
      if (!value) {
        callback(new Error('请输入确认新密码'))
      } else if (value && password && value.trim() !== password.trim()) {
        callback(new Error('两次密码不一致'))
      } else {
        callback()
      }
    },
    handlePasswordInputClick () {
      if (!this.isMobile()) {
        this.state.passwordLevelChecked = true
        return
      }
      this.state.passwordLevelChecked = false
    },
    pwdRequest () {
      const { id, password, newPassword, confirmPassword } = this.ruleForm
      this.submitLoading = true
      userUpdatePwd({ userId: id, password, newPassword, confirmPassword })
        .then(() => {
          this.submitLoading = false
          this.$notification.success({
            message: '提示',
            description: '修改密码成功'
          })
          setTimeout(() => {
            store.dispatch('Logout').then(() => {
              window.location.reload()
            })
          }, 1000)
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    pwdSubmitHandler () {
      const vm = this
      this.$refs[this.tabActive][0].validate((valid) => {
        if (valid) {
          if (this.state.passwordLevel != 3) {
            this.$confirm({
              tilte: '温馨提示',
              content: (
                <p>
                  <span style="color:#FF4E4E">
                    您的密码复杂度太低（密码中必须包含大小写6～20位字母、数字组合）
                  </span>
                  ，请问还要继续提交吗？
                </p>
              ),
              onOk () {
                vm.pwdRequest()
              }
            })
          } else {
            vm.pwdRequest()
          }
        }
      })
    },
    afterVisibleChange () {},
    onClose () {
      this.visible = false
    },
    typeClick (val) {
      console.log(val, 'typeClick')
      this.$refs[this.tabActive][0].clearValidate()
      this.tabActive = val
      this.$nextTick(() => {
        this.$refs[val][0].resetFields()
      })
    },
    open () {
      this.visible = true
      this.ruleForm = { ...this.ruleForm, ...this.userInfo }
    },
    onSubmit () {
      this.$refs[this.tabActive][0].validate((valid) => {
        if (valid) {
          editUser(this.ruleForm).then((res) => {
            console.log(res)
            this.$notification['success']({
              message: '提示',
              description: `${this.ruleForm.id ? '编辑' : '新增'}成功`
            })
            // this.onClose()
            store.dispatch('GetInfo')
          })
        }
      })
    },
    phoneSubmitHandler () {
      const { ruleForm, phoneRuleForm } = this
      this.$refs[this.tabActive][0].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          userUpdatePhone({ ...phoneRuleForm, userId: ruleForm.userId })
            .then((res) => {
              console.log(res)
              this.$notification['success']({
                message: '提示',
                description: '修改成功'
              })
              // this.onClose()
              store.dispatch('GetInfo')
              this.submitLoading = false
            })
            .catch(() => {
              this.submitLoading = false
            })
        }
      })
    },
    updatePwdHandler () {
      userUpdatePwd()
    }
  },
  components: {
    UploadImage
  }
}
</script>

<style lang="less" scoped>
@import url('../../../style/ant-design-variables.less');

/deep/.ant-tabs-tab {
  text-align: left !important;
  &.ant-tabs-tab-active {
    background-color: #f0f8ff;
    border-radius: 2px 0 0 2px;
  }
}
.ant-descriptions-row {
  .ant-descriptions-item {
    border-bottom: 1px solid rgba(228, 228, 228, 0.5);
    margin-bottom: 24px;
  }
  .ant-descriptions-item-label {
    font-weight: 500;
  }
  .ant-descriptions-item-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .user-phone{
      line-height: 42px;
      font-weight: 400;
      height: 42px;
    }
  }
}
.progress {
  display: flex;
  align-items: center;
  .progress-item {
    width: 37px;
    height: 16px;
    background: #ebedf0;
    margin-right: 2px;
    &:last-of-type {
      margin-right: 0;
      border-radius: 0 8px 8px 0;
    }
    &:first-of-type {
      border-radius: 8px 0 0 8px;
    }
  }
}
.error,
.warning,
.success {
  font-size: 18px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #999999;
  margin-left: 14px;
}
.warning {
  color: #666666;
}
.success {
  color: #330000;
}
/deep/.ant-input-password svg {
  font-size: 14px !important;
}
</style>
